﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.IdentityModel.Tokens;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.W.realize;
using MyMES.Read.API.Dtos;
using MySql.Data.MySqlClient;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace MyMES.Read.API.Controllers.WController
{
    [Route("api/[controller]/[action]")]
    [ApiController]
  
    public class ProductInfoController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IBaseRepository<ProductionReport> baseRepository;
        private readonly IBaseRepository<SalesReceipt> baseRepository1;

        public ProductInfoController(IMediator mediator, IBaseRepository<ProductionReport> baseRepository, IBaseRepository<SalesReceipt> baseRepository1)
        {
            this.mediator = mediator;
            this.baseRepository = baseRepository;
            this.baseRepository1 = baseRepository1;
        }

        

        #region 显示信息
        ///<summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [Authorize]
        public async Task<APIResult<List<UserInfo>>> LoginHandle([FromQuery] GetUserCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);

        }

        /// <summary>
        /// 显示供应商信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIPaging<List<Supplier>>> ShowSupplierHandle([FromQuery] GetSupplierCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示等级下拉框
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIResult<List<SupplierLevel>>> GetSupplierLevel([FromQuery] GetSupplierLevelCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示物料产品管理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<Materialmanagement>>> GetMaterialmanagement([FromQuery] GetMaterialmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示物料产品分类信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIResult<List<Materialproductclassification>>> GetMaterialproductclassification([FromQuery] GetMaterialproductclassificationCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }


        /// <summary>
        /// 显示生产任务
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIPaging<List<ProductionTask>>> GetProductionTask([FromQuery] GetProductionTaskCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示生产报工
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIPaging<List<ProductionReport>>> GetProductionReport([FromQuery] GetProductionReportCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示销售出库信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIPaging<List<SalesReceipt>>> GetSaleReceipt([FromQuery] GetSaleReceiptCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示生产退料
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIPaging<List<Productionreturn>>> GetProductionreturn([FromQuery] GetProductionreturnCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示人员信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIPaging<List<Caller>>> GetCaller([FromQuery]GetCallerCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示开票信息
        /// </summary>
        /// <param name="request">开票信息</param>
        /// <param name="cancellationToken">2025-4-14</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIPaging<List<BilingmanagementDTO>>> GetBillingmanagement([FromQuery]GetBillingmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示到票信息
        /// </summary>
        /// <param name="request">到票管理</param>
        /// <param name="cancellationToken">2025年4月16日10:08:44</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIPaging<List<ArrivalmanagementDTO>>> GetArrivalmanagement([FromQuery]GetArrivalmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示销售订单信息
        /// </summary>
        /// <param name="request">销售订单</param>
        /// <param name="cancellationToken">2025年4月14日12:00:17</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIResult<List<Salesordersheet>>> GetSalesordersheet([FromQuery]GetSalesordersheetCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        #endregion

        #region 导出
        /// <summary>
        /// 导出生产报工
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExeclProductionReport()
        {
            APIResult<ProductionReport> result = new APIResult<ProductionReport>();
            result.Code = APIEnum.查询成功;
            result.Msg = "生产报工导出成功";
            var sql = "select * from ProductionReport where IsDelete=false ORDER BY ProductionReportId DESC";
            var list = await baseRepository.SelectAsync(sql);

            //创建工作簿
            IWorkbook workbook = new XSSFWorkbook();

            //依据工作簿创建sheet
            ISheet sheet = workbook.CreateSheet("生产报工");
            //依据sheet创建首行
            IRow row = sheet.CreateRow(0);
            //在创建好的行中创建首行单元格
            row.CreateCell(0).SetCellValue("报工类型");
            row.CreateCell(1).SetCellValue("工作站");
            row.CreateCell(2).SetCellValue("生产工单编号");
            row.CreateCell(3).SetCellValue("产品物料编号");
            row.CreateCell(4).SetCellValue("产品物料名称");
            row.CreateCell(5).SetCellValue("规格型号");
            row.CreateCell(6).SetCellValue("报工数量");
            row.CreateCell(7).SetCellValue("报工人");
            row.CreateCell(8).SetCellValue("报工时间");
            row.CreateCell(9).SetCellValue("审核人");
            row.CreateCell(10).SetCellValue("状态");
            row.CreateCell(11).SetCellValue("生产任务编号");
            row.CreateCell(12).SetCellValue("单位");
            row.CreateCell(13).SetCellValue("备注");
            row.CreateCell(14).SetCellValue("逻辑删除");

            //行编号
            int index = 1;
            foreach (var item in list.ToList())
            {
                //Sheet表中的第二行完成数据遍历
                //创建新行
                row = sheet.CreateRow(index);

                //将所有数据依次写入行中
                row.CreateCell(0).SetCellValue(item.ReportTypeId);
                row.CreateCell(1).SetCellValue(item.WorkStation);
                row.CreateCell(2).SetCellValue(item.ProductionId);
                row.CreateCell(3).SetCellValue(item.ProductMaterialCode);
                row.CreateCell(4).SetCellValue(item.ProductMaterialName);
                row.CreateCell(5).SetCellValue(item.SpecificationModel);
                row.CreateCell(6).SetCellValue(item.QuantityReported);
                row.CreateCell(7).SetCellValue(item.Caller);
                row.CreateCell(8).SetCellValue(item.CallTime.ToString("yyyy-MM-dd"));
                row.CreateCell(9).SetCellValue(item.Auditor);
                row.CreateCell(10).SetCellValue(item.Status);
                row.CreateCell(11).SetCellValue(item.ProductionTaskNumber);
                row.CreateCell(12).SetCellValue(item.Unit);
                row.CreateCell(13).SetCellValue(item.Remark);
                row.CreateCell(14).SetCellValue(item.IsDelete);

                //换行
                index++;
            }

            //excel
            byte[] buffer;
            //使用内存流出Excel的内容
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                buffer = ms.ToArray();
            }
            //导出Excel  using Microsoft.AspNetCore.StaticFiles;
            string excelMime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];


            //导出
            return File(buffer, excelMime, "生产报工.xlsx");
        }

        /// <summary>
        /// 导出销售出库单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExeclSalesReceipt()
        {
            APIResult<SalesReceipt> result = new APIResult<SalesReceipt>();
            result.Code = APIEnum.查询成功;
            result.Msg = "销售出库单导出成功";
            var sql = "select * from SalesReceipt where IsDelete=false ORDER BY SalesReceiptId DESC";
            var list = await baseRepository1.SelectAsync(sql);

            //创建工作簿
            IWorkbook workbook = new XSSFWorkbook();

            //依据工作簿创建sheet
            ISheet sheet = workbook.CreateSheet("销售出库单");
            //依据sheet创建首行
            IRow row = sheet.CreateRow(0);
            //在创建好的行中创建首行单元格
            row.CreateCell(0).SetCellValue("出库单编号");
            row.CreateCell(1).SetCellValue("出库单名称");
            row.CreateCell(2).SetCellValue("销售订单编号");
            row.CreateCell(3).SetCellValue("客户编号");
            row.CreateCell(4).SetCellValue("客户名称");
            row.CreateCell(5).SetCellValue("出库日期");
            row.CreateCell(6).SetCellValue("单据状态");

            //行编号
            int index = 1;
            foreach (var item in list.ToList())
            {
                //Sheet表中的第二行完成数据遍历
                //创建新行
                row = sheet.CreateRow(index);

                //将所有数据依次写入行中
                row.CreateCell(0).SetCellValue(item.OutboundOrderCode);
                row.CreateCell(1).SetCellValue(item.OutboundOrderName);
                row.CreateCell(2).SetCellValue(item.SalesOrderNumber);
                row.CreateCell(3).SetCellValue(item.CustomerCode);
                row.CreateCell(4).SetCellValue(item.CustomerName);
                row.CreateCell(5).SetCellValue(item.OutboundDate.ToString("yyyy-MM-dd"));
                row.CreateCell(6).SetCellValue(item.DocumentStatus);
                

                //换行
                index++;
            }

            //excel
            byte[] buffer;
            //使用内存流出Excel的内容
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                buffer = ms.ToArray();
            }
            //导出Excel  using Microsoft.AspNetCore.StaticFiles;
            string excelMime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];


            //导出
            return File(buffer, excelMime, "销售出库单.xlsx");
        }

        #endregion

       
    }
}
